package com.jayqqaa12.oauth2;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jayqqaa12.jbase.jfinal.ext.model.Model;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.ehcache.CacheKit;

@Component
@TableBind(tableName = "oauth2_token")
public class Token extends Model<Token> {
	private static final long serialVersionUID = 7752894507977921216L;
	@Autowired
	Client clientDao;

	/**
	 * 判断 是否 token 是否 有效 并删除无效 token 有缓存
	 * 
	 * @param token
	 * @return
	 */
	public boolean checkToken(String token) {
		boolean result = false;

		Token t = findFirstByCache(token, "where token=?", token);

		if (t != null) {
			if (t.getLong("expires") > System.currentTimeMillis()) result = true;
			else delete(token);
		}

		return result;
	}
	
	
	public void delete(String token) {
		
		Token t = findFirstByCache(token, "where token=?", token);
		if (t != null) {
			t.delete();
			CacheKit.remove(tableName, token);
		}
		
	}

	

	public String getToken(Token newToken) throws OAuthSystemException {

		String token = new OAuthIssuerImpl(new MD5Generator()).accessToken();
		long expires = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 30 * 10;
		Token t = findFirstByWhere("where uid=? and client_id=?", newToken.get("uid"), newToken.get("client_id"));
		if (t != null) {
			if (t.getLong("expires") > System.currentTimeMillis()) token = t.getStr("token");
			else t.set("token", token).set("expires", expires).update();
		} else {
			newToken.set("token", token).set("expires", expires).save();
		}

		return token;
	}






}
